package cn.tedu.v2;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 聊天室 Version 1
 * 功能：1.客户端-指定ip，端口号
 *      2.客户端给服务器发送文本
 *      3.客户端完成标准IO
 *      【新增】4.捕获异常，打印异常信息--异常全部抓住，用户明确提示
 *      5.关闭socket
 */
public class Client {
    private Socket socket;
    public Client() throws IOException {

try {
    socket = new Socket("172.21.69.1", 1019);
  }catch (UnknownHostException e){//用户地址出问题异常
    System.out.println("IP地址有问题，请询问服务器端！");
  } catch (IOException e) {//IO异常：连接失败，客户端主动退出了
    System.out.println("客户端主动退出了：断开连接");
}
  }
    //3.创建方法 start()  逻辑  使用IO流 写出
    public void start(){
        PrintWriter pw=null;//滞空流--赋值--关流

        try {
            OutputStream os = socket.getOutputStream();
            //InputStream is= socket.getInputStream();

            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF8");
            //InputStreamReader isr=new InputStreamReader(is,"UTF8");

            BufferedWriter bw = new BufferedWriter(osw);
            //BufferedReader br=new BufferedReader(isr);
            //PrintWriter pw=new PrintWriter(bw,true);

            pw = new PrintWriter(bw, true);

            System.out.println("客户端用户：请输入文字：");
            Scanner input = new Scanner(System.in);

            while (true) {
                String say = input.nextLine();
                pw.println(say);
                System.out.println("写出完毕");
            }
        }catch (UnsupportedEncodingException e) {
            System.out.println("客户端与服务器端：字符集不一致！");
        }catch (IOException e) {
            System.out.println("客户端断开了连接");
        }finally {
            //关闭流 关闭socket
            if (pw!=null)
                pw.close();
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("客户端离开");
            }
        }
        /*while (true){
            String str=br.readLine();
            System.out.println("服务器说话："+str);
        }*/
    }
    public static void main(String[] args) throws IOException {
        Client client=new Client();
        client.start();
    }
}


